import os
from PIL import Image

def generate_thumbnails(directory, size=(180, 180), quality=35):
    for root, dirs, files in os.walk(directory):
        for file in files:
            if file.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp')):
                file_path = os.path.join(root, file)
                try:
                    with Image.open(file_path) as img:
                        img.thumbnail(size)
                        thumb_path = os.path.join(root, f"thumb_{file}")

                        # 压缩并保存图片
                        img.save(
                            thumb_path,
                            optimize=True,
                            quality=quality,
                            dpi=(180, 180)  # 可选：设置分辨率为 72dpi
                        )
                        print(f"Thumbnail saved at: {thumb_path}")
                except Exception as e:
                    print(f"Error processing {file_path}: {e}")

if __name__ == '__main__':
    file_dir = '/Users/binny/Downloads/商城材料'
    generate_thumbnails(file_dir)
